#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
from dataclasses import dataclass
from typing import List, Dict, Optional
from datetime import datetime, timedelta

@dataclass
class SubtitleItem:
    """字幕项"""
    start_time: float  # 开始时间（秒）
    end_time: float    # 结束时间（秒）
    text: str         # 字幕文本

class SubtitleUtil:
    @staticmethod
    def parse_json(json_content: str) -> List[SubtitleItem]:
        """解析JSON格式的字幕文件"""
        data = json.loads(json_content)
        subtitle_list = []
        
        for item in data['body']:
            subtitle = SubtitleItem(
                start_time=item['from'],
                end_time=item['to'],
                text=item['content']
            )
            subtitle_list.append(subtitle)
        
        return subtitle_list
    
    @staticmethod
    def convert_to_srt(subtitle_list: List[SubtitleItem], output_path: str) -> None:
        """将字幕转换为SRT格式"""
        with open(output_path, 'w', encoding='utf-8') as f:
            for i, item in enumerate(subtitle_list, 1):
                start_time = str(timedelta(seconds=item.start_time)).replace('.', ',')
                end_time = str(timedelta(seconds=item.end_time)).replace('.', ',')
                f.write(f"{i}\n{start_time} --> {end_time}\n{item.text}\n\n")
    
    @staticmethod
    def convert_to_ass(subtitle_list: List[SubtitleItem], output_path: str) -> None:
        """将字幕转换为ASS格式"""
        with open(output_path, 'w', encoding='utf-8') as f:
            # 写入ASS头部
            f.write("""[Script Info]
ScriptType: v4.00+
PlayResX: 1920
PlayResY: 1080
Timer: 100.0000

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,微软雅黑,54,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,20,20,20,1

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
""")
            
            # 写入字幕
            for item in subtitle_list:
                start_time = str(timedelta(seconds=item.start_time)).replace('.', '.')
                end_time = str(timedelta(seconds=item.end_time)).replace('.', '.')
                f.write(f"Dialogue: 0,{start_time},{end_time},Default,,0,0,0,,{item.text}\n") 